package com.test.ext;

import com.test.bean.Rainbow;
import com.test.bean.Yellow;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.stereotype.Component;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2018/12/1 11:15
 */
@Component
public class MyBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {

    /**
     * BeanDefinitionRegistry: bean定义信息的保存中心，以后BeanFactory就是按照BeanDefinitionRegistry里面保存的每一个bean定义信息创建bean实例
     *
     * @param registry
     * @throws BeansException
     */
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        System.out.println("postProcessBeanDefinitionRegistry...");
        System.out.println("bean count by new method:" + registry.getBeanDefinitionCount());
        BeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(Rainbow.class).getBeanDefinition();
        registry.registerBeanDefinition("rainbow", beanDefinition);
        registry.registerBeanDefinition("hello", new RootBeanDefinition(Yellow.class));
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        System.out.println("postProcessBeanFactory...");
        System.out.println("bean count " + beanFactory.getBeanDefinitionCount());
    }
}
